#!/bin/csh
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#   TROPICAL STORM DETECTION 
#%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

#===============================================================
# --- CHECK ARGUMENTS
#===============================================================

set nargin = $#argv
set xdir = ""

if ($nargin < 2) then
    echo
    echo "USAGE: " $0 " <inputfile> <outputdir>"
    echo
    echo "ARGUMENTS:"
    echo "\t<inputfile>: full path to input netCDF file"
    echo
    echo "\t<outputdir>: full path to output directory for multiple files; will be created if it does not exist"
    echo
    echo "\t<executabledir>: full path to directory with tstorms and trajectory executables"
    echo "\t\t\t(optional: necessary only if not already in PATH)"
    echo
    exit -1
else
    set fin = $1
    set dir_out = $2
    if ($nargin > 2) then
	set xdir = $3
    endif
endif

echo "inputfile = " $fin
echo "outputdir = " $dir_out

# n: only count potential tropical storms at isolated time steps
# y: after finding potential storms, link them into trajectories
set do_traj = y

# year, used as suffix for output files
#set year    = $1 

if ( ! -e $dir_out  ) mkdir -p $dir_out

#===============================================================
# --- SET SOME PATHNAMES
#===============================================================

# --- executables
if ($xdir == "") then
    set tstorms = tstorms_drive.exe
    set trajectory = trajectory.exe
else
    echo "executabledir = " $xdir
    set tstorms    = ${xdir}/tstorms_drive.exe
    set trajectory = ${xdir}/trajectory.exe
endif

# --- output data
set fcyc  = ${dir_out}/cyclones_out    # storm days
set ftraj = ${dir_out}/traj_out        # trajectories
set fori  = ${dir_out}/ori_out         # initial positions
set fstat = ${dir_out}/traj_stat_out   # total counts

#===============================================================
# --- TRAJECTORY ANALYSIS
#===============================================================
if ( $do_traj == y ) then

# --- get executable
#cp $trajectory  trajectory.exe

#rm -f    cyclones
#cp $fcyc ${dir_out}/cyclones

cp $fcyc cyclones

if ( ! -e $dir_out/nml_trajectory  ) then
cat << eof > ${dir_out}/nml_trajectory
 &nml_trajectory
      wcrit =  10.0,
      rcrit =  400.0,
     nwcrit =  8,
    do_filt = .true.,
 /end
eof
endif

$trajectory < ${dir_out}/nml_trajectory

head -16  stats

# move to output directory
mv   ori  $fori
mv  traj  $ftraj
mv stats  $fstat

# delete copy of cyclones file
rm -f cyclones

endif




